﻿// <copyright file="CostInfoController.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

namespace MesAPI.Controllers.Maintenance
{
    using System;
    using System.Globalization;
    using System.Linq;
    using MesAPI.Extensions.AuthContext;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using PublicData;
    using PublicModelsAndEntities.Models.MainsortRecord;
    using XinjeMesProgram.Entities;
    using XinjeMesProgram.Entities.BookInfo;
    using XinjeMesProgram.Entities.Function;

    /// <summary>
    /// 费用.
    /// </summary>
    [ApiController]
    [Authorize]
    public class CostInfoController : ControllerBase
    {
#pragma warning disable SA1000 // Keywords should be spaced correctly
#pragma warning disable CS8602 // 解引用可能出现空引用。
#pragma warning disable CS8604 // 引用类型参数可能为 null。
        private readonly ResponseModel response = new();

        /// <summary>
        /// 获取费用页面列表 .
        /// </summary>
        /// <param name="pageSize">每页记录数 .</param>
        /// <param name="currentPage">当前页码 .</param>
        /// <param name="oneDimensionalCode">一维码 .</param>
        /// <param name="applyTime">6.</param>
        /// <param name="name">3.</param>
        /// /// <param name="chaoqi">收费状态 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/cost/costList")]
        [HttpGet]
        public ResponseModel GetCostOrderList(int pageSize, int currentPage, string? oneDimensionalCode, string? applyTime, string? name, string? chaoqi)
        {
            using (FactoryMesContext factoryMes = new())
            {
                var query = from sr in factoryMes.MainsortRecord
                            join rp in factoryMes.RepairProduct on sr.ID equals rp.ProductId
                            join cost in factoryMes.MaintenanceCost on rp.ProductId equals cost.ID
                            where sr.State == "4"
                            orderby cost.ApplyTime descending, sr.SortingDate descending
                            select new CostListInfoModel
                            {
                                Id = sr.ID,
                                ApplyTime = cost.ApplyTime != null ? cost.ApplyTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : string.Empty,
                                Name = sr.Name,
                                CustomerLevel = sr.CustomerLevel == 0 ? "KA级客户" : (sr.CustomerLevel == 1 ? "A级客户" : (sr.CustomerLevel == 2 ? "代理商" : (sr.CustomerLevel == 3 ? "终端客户" : "无"))), // 客户等级
                                Product_model = sr.Product_Model,
                                One_dimensional_code = sr.One_Dimensional_Code,
                                FailureCause = string.Empty, // 故障原因
                                Product_handle = string.Empty, // 产品处理
                                Guarantee = sr.Guarantee,
                                Product_Name = sr.Product_Name,
                                SecondaryRepairsOr = sr.SecondaryRepairsOr == "是" ? "是" : string.Empty, // 是否二次维修
                                Repairornot = rp.RepairOr,
                                Notes = rp.Notes,
                                Receivable = cost.Receivable,
                                NetReceipts = cost.NetReceipts,
                                State = sr.State,
                                CostNumber = cost.Context,
                            };
                if (!string.IsNullOrEmpty(oneDimensionalCode))
                {
                    query = query.Where(x => x.One_dimensional_code.Contains(oneDimensionalCode));
                }

                if (!string.IsNullOrEmpty(applyTime))
                {
                    query = query.Where(x => x.Product_model.Contains(applyTime));
                }

                if (!string.IsNullOrEmpty(name))
                {
                    query = query.Where(x => x.Name.Contains(name));
                }

                var result = query.ToList();
                for (int i = 0; i < result.Count; i++)
                {
                    var info0 = factoryMes.MainsortRecord.FirstOrDefault(x => x.ID == result[i].Id);
                    var info = factoryMes.MaintenanceCost.FirstOrDefault(x => x.ID == result[i].Id);

                    // result[i].Product_handle = info.Context.Split("error_deal\":\"")[1].Split("\",\"")[0];
                    result[i].Product_handle = info.Context.Split(info0.One_Dimensional_Code)[1].Split("error_deal\":\"")[1].Split("\"")[0];

                    // result[i].FailureCause = info.Context.Split("error_reason\":\"")[1].Split("\",\"")[0];
                    result[i].FailureCause = info.Context.Split(info0.One_Dimensional_Code)[1].Split("error_reason\":\"")[1].Split("\"")[0];
                }

                this.response.SetData(result.ListPaged(currentPage, pageSize), result.Count);
            }

            return this.response;
        }

        /// <summary>
        /// 保存费用应收实收 .
        /// </summary>
        /// <param name="editCost">需求主体 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/cost/costEdit")]
        [HttpPost]
        public ResponseModel EditCost(EditCostMoneyModel editCost)
        {
            using (FactoryMesContext factoryMes = new())
            {
                var info = factoryMes.MaintenanceCost.FirstOrDefault(x => x.ID == editCost.id);
                if (info != null)
                {
                    info.Receivable = editCost.receivable;
                    info.NetReceipts = editCost.netReceipts;
                    factoryMes.SaveChanges();
                }
                else
                {
                    this.response.SetError("没找到此单据");
                }
            }

            return this.response;
        }

        /// <summary>
        ///  改变产品状态 .
        /// </summary>
        /// <param name="editCost">需求主体 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/cost/changeState")]
        [HttpPost]
        public ResponseModel EditState(EditCostStateModel editCost)
        {
            using (FactoryMesContext factoryMes = new())
            {
                var info = factoryMes.MainsortRecord.FirstOrDefault(x => x.ID == editCost.id);

                if (info != null)
                {
                    info.State = "5";
                }

                var query = factoryMes.MaintenanceCost.FirstOrDefault(x => x.ID == editCost.id);

                if (query != null)
                {
                    query.UnlockTime = DateTime.Now;
                    query.PayTime = query.ApplyTime == null ? 0 : (DateTime.Now - query.ApplyTime).Value.Days;
                }

                // 维修开始
                var issue = factoryMes.RepairProduct.FirstOrDefault(x => x.ProductId == editCost.id);
                if (issue != null)
                {
                    issue.MaintenanceEntryTime = DateTime.Now;
                }

                factoryMes.SaveChanges();
            }

            return this.response;
        }

        /// <summary>
        /// 是否维修 .
        /// </summary>
        /// <param name="repairor">需求主体 .</param>
        /// <param name="id">1.</param>
        /// <param name="mark">2 .</param>
        /// <param name="notes">3 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/cost/Repairor")]
        [HttpGet]
        public ResponseModel EditState(string? repairor, string? id, string? mark, string? notes)
        {
            using (FactoryMesContext factoryMes = new())
            {
                // 维修
                var issue = factoryMes.RepairProduct.FirstOrDefault(x => x.ProductId == id);
                if (mark == "0")
                {
                    if (issue != null)
                    {
                        issue.RepairOr = repairor;
                    }
                }
                else if (mark == "1")
                {
                    issue.Notes = notes;
                }

                factoryMes.SaveChanges();  // 保存
            }

            return this.response;
        }

        /// <summary>
        /// 发货超期统计 .
        /// </summary>
        /// <returns> .</returns>
        [Route("/api/v1/reForms/costView")]
        [HttpGet]
        public ResponseModel EditState()
        {
            AuthContextUser currentUser = AuthContextService.CurrentUser;
            using var context = new FactoryMesContext();
            int[] str = { 0, 0 };

            var query = from sr in context.MainsortRecord
                        join m in context.MaintenanceCost
                          on sr.ID equals m.ID into dGroup
                        from m in dGroup.DefaultIfEmpty()
                        where sr.State == "4"
                        select new Costvirw
                        {
                            applyTime = m.ApplyTime,
                        };

            List<Costvirw> result = query.ToList();
            str[0] = result.Where(x => x.applyTime != null && (DateTime.Now - x.applyTime).Value.Days > 15).Count();
            str[1] = result.Where(x => x.applyTime != null && (DateTime.Now - x.applyTime).Value.Days <= 15).Count();
            this.response.SetData(str);
            return this.response;
        }
    }
}
